package com.ebt.m.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.account.AccountHttps;
import com.ebt.m.account.json.AccountResponse;
import com.ebt.m.account.json.ValidateCodeCheckRequest;
import com.ebt.m.account.json.ValidateCodeCheckResponse;
import com.ebt.m.account.json.ValidateCodeSendResponse;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.commons.model.data.BaseDataResult;
import com.ebt.m.event.LoginEvent;
import com.ebt.m.jpush.JPushUtil;
import com.ebt.m.proposal_v2.widget.dialog.EBTProgressDialog;
import com.ebt.m.utils.CountDownManager;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.utils.android.EBTUserInfoHelper;
import com.ebt.m.commons.utils.NetUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wanglu on 2017/8/21.
 */

public class CancelAuthenticationActivity extends BaseToolBarActivity {
    @BindView(R.id.view_count_down)
    View view_count_down;
    @BindView(R.id.view_step0)
    View view_step0;
    @BindView(R.id.button_step0)
    Button button_step0;
    @BindView(R.id.text_view_vcode_hint)
    TextView text_view_vcode_hint;
    @BindView(R.id.text_view_title_hint)
    TextView text_view_title_hint;

    @BindView(R.id.edit_text_vc)
    EditText edit_text_vc;

    private EBTProgressDialog mProgressDialog;

    private static String mValidateId;
    private boolean mHasSend = false;

    private CountDownManager.CountDownListener mCountDownListener;
    private CountDownManager mCountDownManager;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cancel_authentication);
        mCountDownManager = CountDownManager.getInstance();
        ButterKnife.bind(this);
        initProgressDialog();
        initView();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if (mCountDownManager.isCountingDown()) {
            initVCodeHintForCountingDown();
            return;
        }
        sendVCodeRequest();
    }

    public void initView() {
        setTitle("取消认证");
        mCountDownListener = new CountDownManager.CountDownListener() {
            @Override
            public void onTick(long remainMillisSecond) {
                int countdownSecond = (int) (remainMillisSecond / 1000);
                updateVCodeHint(mHasSend, String.valueOf(countdownSecond));
            }

            @Override
            public void onFinish() {
                updateVCodeHint(mHasSend, "");
            }
        };
        mCountDownManager.setCountDownListener(mCountDownListener);

        edit_text_vc.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void afterTextChanged(Editable editable) {
                onTextChangeVC(editable.toString());
            }
        });
        updateButtonStep0State(edit_text_vc.getText().toString().trim(), mValidateId);

    }

    private void initVCodeHintForCountingDown() {
        text_view_vcode_hint.setText("重新发送");
        text_view_vcode_hint.setTextColor(getResources().getColor(R.color.btn_green_disable));
    }

    private void updateVCodeHint(boolean hasSend, String countDownHint) {
        if (TextUtils.isEmpty(countDownHint)) {
            text_view_vcode_hint.setText("重新发送");
            text_view_vcode_hint.setTextColor(getResources().getColor(R.color.btn_green_normal));
        } else {
            text_view_vcode_hint.setText("重新发送(" + countDownHint + ")");
            text_view_vcode_hint.setTextColor(getResources().getColor(R.color.btn_green_disable));
        }
    }

    private void updateTitleHintView(String phoneNumber) {
        //已向手机号 100000000 发送短信验证码
        String str1 = "已向手机号 ";
        String str2 = " 发送短信验证码";
        SpannableString spannableString = new SpannableString(str1 + phoneNumber + str2);

        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#666666"));
        RelativeSizeSpan sizeSpan = new RelativeSizeSpan(1.2f);

        spannableString.setSpan(colorSpan, str1.length(), str1.length() + phoneNumber.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(sizeSpan, str1.length(), str1.length() + phoneNumber.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        text_view_title_hint.setText(spannableString);
    }

    private void onTextChangeVC(String s) {
        updateButtonStep0State(s, mValidateId);
    }

    private void updateButtonStep0State(String vCode, String validateId) {
        if (TextUtils.isEmpty(vCode)) {
            button_step0.setEnabled(false);
        } else {
            button_step0.setEnabled(true);
        }
    }

    @OnClick(R.id.button_step0)
    public void onStep0ButtonClicked() {
        //校对验证码
        if (!NetUtils.isNetworkAvailable(this)) {
            ToastUtil.showToast(getString(R.string.network_fail));
            return;
        }

        if (TextUtils.isEmpty(mValidateId)) {
            ToastUtil.showToast("验证码无效，请重新获取");
            return;
        }

        //校验验证码
        ValidateCodeCheckRequest request = new ValidateCodeCheckRequest(AppContext.getCurrentUser().getPhone(),
                mValidateId,
                edit_text_vc.getText().toString().trim());
        EBTAPI mApi = AppInitService.getEbtApi();
        mApi.checkValidateCode(request)
                .flatMap(checkResult -> {
                    ValidateCodeCheckResponse validateCodeCheckResponse = checkResult.getData();
                    if (validateCodeCheckResponse.isSuccess) {
                        return mApi.cancelAuth();
                    } else {
                        runOnUiThread(() -> com.ebt.m.commons.utils.ToastUtil.show(this, "验证码校验失败"));
                        return Observable.just("failed");
                    }
                })
                .filter(cancelResult -> !cancelResult.equals("failed"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(cancelResult -> {
                    hideProgress();
                    BaseDataResult<AccountResponse> accountResponse = (BaseDataResult) cancelResult;
                    if (accountResponse != null && accountResponse.getData() != null && accountResponse.getData().isSuccess()) {
                        com.ebt.m.commons.utils.ToastUtil.show(this, "取消认证成功");
                        loginOutAction();
                    } else {
                        com.ebt.m.commons.utils.ToastUtil.show(this, "取消认证失败");
                    }

                }, throwable -> {
                    Logger.e(throwable.getMessage());
                    hideProgress();
                    NetUtils.checkHttpException(this, throwable);
                });

    }

    @OnClick(R.id.view_count_down)
    public void onGetVCodeClicked() {
        if (!NetUtils.isNetworkAvailable(this)) {
            ToastUtil.showToast(getString(R.string.network_fail));
            return;
        }
        if (mCountDownManager.isCountingDown()) {
            ToastUtil.showToast("请稍后再发送验证码");
            return;
        }
        sendVCodeRequest();
    }

    private void sendVCodeRequest() {
        //没有手机号，无法接收验证码短信
        if (TextUtils.isEmpty(AppContext.getCurrentUser().getPhone())) {
            ToastUtil.showToastL("请先绑定手机");
            return;
        }
        showProgress("正在获取验证码...");
        mCountDownManager.startCountDown();
        mHasSend = true;
        //发送验证码
        AccountHttps.getInstance().sendValidateCode(
                AppContext.getCurrentUser().getPhone(),
                getSendVCodeSubscriber(), this);
    }

    //发送验证码
    private Observer getSendVCodeSubscriber() {
        return new Observer<BaseDataResult<ValidateCodeSendResponse>>() {

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtils.checkHttpException(CancelAuthenticationActivity.this, e);
                hideProgress();
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseDataResult<ValidateCodeSendResponse> responseJson) {
                hideProgress();
                if (responseJson == null || responseJson.getData() == null) {
                    ToastUtil.showSendVCodeErrorMessage(responseJson);
                    return;
                }
                if (responseJson.getData() != null) {
                    ValidateCodeSendResponse validateCodeSendResponse = responseJson.getData();
                    if (validateCodeSendResponse.isSuccess) {
                        mValidateId = validateCodeSendResponse.getValidateId();
                        updateTitleHintView(AppContext.getCurrentUser().getPhone());
                    } else {
                        ToastUtil.showSendVCodeErrorMessage(responseJson);
                    }
                }
            }
        };
    }

    private void loginOutAction() {
        String userName = AppContext.getCurrentUser().getPhone();
        AppContext.clearLoginInfo(this);
        EventBus.getDefault().post(new LoginEvent(false));
        //退出登录
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.setAction(LoginActivity.ACTION_FROM_RESETPWD);
        intent.putExtra(LoginActivity.USERNAME_KEY, userName);
        startActivity(intent);
        mValidateId = "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginEvent event) {
        if (event == null) {
            return;
        }
        if (!event.login) {
            this.finish();
        }
    }

    private void initProgressDialog() {
        mProgressDialog = new EBTProgressDialog(this);
    }

    private void showProgress(String message) {
        if (mProgressDialog != null && !mProgressDialog.isShowing()) {
            mProgressDialog.setMessage(message);
            mProgressDialog.show();
        }
    }

    private void hideProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }
}
